<template>
  <view class="account-settings-page">
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="back-icon">&lt;</text>
      </view>
      <text class="page-title">账号设置</text>
    </view>
    
    <view class="settings-container">
      <!-- 基本信息设置 -->
      <view class="settings-section">
        <view class="section-title">基本信息</view>
        <view class="settings-list">
          <view class="settings-item" @tap="navigateTo('avatar')">
            <view class="item-label">头像</view>
            <view class="item-right">
              <image class="avatar-preview" :src="userInfo.avatar" mode="aspectFill"></image>
              <text class="item-arrow">›</text>
            </view>
          </view>
          
          <view class="settings-item" @tap="navigateTo('nickname')">
            <view class="item-label">昵称</view>
            <view class="item-right">
              <text class="item-value">{{ userInfo.nickname }}</text>
              <text class="item-arrow">›</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 联系方式设置 -->
      <view class="settings-section">
        <view class="section-title">账号安全</view>
        <view class="settings-list">
          <view class="settings-item" @tap="navigateTo('phone')">
            <view class="item-label">手机号码</view>
            <view class="item-right">
              <text class="item-value">{{ maskPhone(userInfo.phone) }}</text>
              <text class="item-arrow">›</text>
            </view>
          </view>
          
          <view class="settings-item" @tap="navigateTo('password')">
            <view class="item-label">修改密码</view>
            <view class="item-right">
              <text class="item-arrow">›</text>
            </view>
          </view>
          
          <view class="settings-item" @tap="navigateTo('login-devices')">
            <view class="item-label">登录设备管理</view>
            <view class="item-right">
              <text class="item-arrow">›</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 将账号安全和账号绑定合并为账号与安全 -->
      <view class="settings-section">
        <view class="section-title">账号绑定</view>
        <view class="settings-list">
          <view class="settings-item" @tap="navigateTo('wx-bind')">
            <view class="item-left">
              <text class="social-icon wx">微信</text>
              <text class="item-label">微信</text>
            </view>
            <view class="item-right">
              <text class="item-value">{{ userInfo.wxBound ? '已绑定' : '未绑定' }}</text>
              <text class="item-arrow">›</text>
            </view>
          </view>
          
          <view class="settings-item" @tap="navigateTo('wb-bind')">
            <view class="item-left">
              <text class="social-icon wb">微博</text>
              <text class="item-label">微博</text>
            </view>
            <view class="item-right">
              <text class="item-value">{{ userInfo.wbBound ? '已绑定' : '未绑定' }}</text>
              <text class="item-arrow">›</text>
            </view>
          </view>
          
          <view class="settings-item" @tap="navigateTo('qq-bind')">
            <view class="item-left">
              <text class="social-icon qq">QQ</text>
              <text class="item-label">QQ</text>
            </view>
            <view class="item-right">
              <text class="item-value">{{ userInfo.qqBound ? '已绑定' : '未绑定' }}</text>
              <text class="item-arrow">›</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 账号注销 -->
      <view class="delete-account" @tap="confirmDeleteAccount">
        <text>注销账号</text>
      </view>
    </view>
    
    <!-- 自定义昵称修改弹框 -->
    <view class="nickname-popup" v-if="showNicknamePop">
      <view class="popup-mask" @tap="closeNicknamePopup"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">修改昵称</text>
          <view class="close-btn" @tap="closeNicknamePopup">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="popup-body">
          <view class="input-wrapper">
            <input 
              type="text" 
              class="nickname-input" 
              v-model="newNickname" 
              placeholder="请输入新昵称" 
              maxlength="16"
              focus
            />
          </view>
          <text class="input-tip">昵称最多支持16个字符</text>
        </view>
        <view class="popup-footer">
          <view class="cancel-btn" @tap="closeNicknamePopup">取消</view>
          <view class="confirm-btn" @tap="confirmNickname">确定</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 当前活跃的设置项
const activeTab = ref('');

// 用户信息
const userInfo = ref({
  nickname: '张三',
  avatar: '../../../image/R.jpg',
  phone: '13812345678',
  wxBound: true,
  wbBound: false,
  qqBound: true
});

// 页面加载时执行
onMounted(() => {
  loadUserInfo();
  checkRouteParams();
});

// 检查路由参数
const checkRouteParams = () => {
  const query = uni.getSystemInfoSync().platform === 'devtools' 
    ? uni.$route.query 
    : getQuery();
    
  if (query && query.tab) {
    activeTab.value = query.tab;
    console.log('当前活跃标签:', activeTab.value);
    
    // 根据tab参数自动导航到对应设置项
    setTimeout(() => {
      navigateTo(activeTab.value);
    }, 100);
  }
};

// 获取URL查询参数
const getQuery = () => {
  try {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    return currentPage.options || {};
  } catch (e) {
    console.error('获取页面参数失败:', e);
    return {};
  }
};

// 加载用户信息
const loadUserInfo = () => {
  // 实际应用中这里应该从API获取用户信息
  console.log('加载用户信息');
  
  // 尝试从本地存储获取用户信息
  try {
    const savedUserInfo = uni.getStorageSync('userInfo');
    if (savedUserInfo) {
      userInfo.value = JSON.parse(savedUserInfo);
      console.log('从本地存储加载用户信息成功');
    }
  } catch (e) {
    console.error('从本地存储加载用户信息失败', e);
  }
};

// 保存用户信息到本地存储
const saveUserInfo = () => {
  try {
    uni.setStorageSync('userInfo', JSON.stringify(userInfo.value));
    console.log('用户信息保存到本地存储成功');
  } catch (e) {
    console.error('用户信息保存到本地存储失败', e);
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1
  });
};

// 昵称修改弹框相关变量
const showNicknamePop = ref(false);
const newNickname = ref('');

// 显示昵称修改弹框
const showNicknamePopup = () => {
  newNickname.value = userInfo.value.nickname;
  showNicknamePop.value = true;
};

// 关闭昵称修改弹框
const closeNicknamePopup = () => {
  showNicknamePop.value = false;
};

// 确认修改昵称
const confirmNickname = () => {
  if (newNickname.value.trim()) {
    // 更新昵称
    userInfo.value.nickname = newNickname.value.trim();
    
    // 保存更新后的用户信息
    saveUserInfo();
    
    // 显示成功提示
    uni.showToast({
      title: '昵称修改成功',
      icon: 'success'
    });
    
    // 关闭弹框
    closeNicknamePopup();
  } else {
    // 昵称不能为空
    uni.showToast({
      title: '昵称不能为空',
      icon: 'none'
    });
  }
};

// 导航到各个设置子页面
const navigateTo = (page) => {
  // 记录当前活跃标签
  activeTab.value = page;
  
  if (page === 'password') {
    // 打开修改密码页面
    uni.navigateTo({
      url: '/pages/profile/settings/password'
    });
    return;
  }
  
  if (page === 'avatar') {
    // 打开头像设置页面
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        // 在实际应用中，这里应该上传头像到服务器
        // 这里仅作为演示，直接更新本地头像
        userInfo.value.avatar = tempFilePath;
        
        // 保存更新后的用户信息
        saveUserInfo();
        
        uni.showToast({
          title: '头像更新成功',
          icon: 'success'
        });
      }
    });
    return;
  }
  
  if (page === 'nickname') {
    // 打开自定义昵称设置弹框
    showNicknamePopup();
    return;
  }
  
  if (page === 'phone') {
    // 打开手机号码设置页面
    uni.navigateTo({
      url: '/pages/profile/settings/phone'
    });
    return;
  }
  
  if (page === 'login-devices') {
    // 打开登录设备管理页面
    uni.showModal({
      title: '登录设备管理',
      content: '您当前只有1台活跃设备。\n设备名称：当前设备\n登录时间：' + new Date().toLocaleString(),
      confirmText: '确定',
      showCancel: false
    });
    return;
  }
  
  if (page === 'wx-bind' || page === 'wb-bind' || page === 'qq-bind') {
    // 社交账号绑定/解绑
    const platformMap = {
      'wx-bind': { name: '微信', key: 'wxBound' },
      'wb-bind': { name: '微博', key: 'wbBound' },
      'qq-bind': { name: 'QQ', key: 'qqBound' }
    };
    
    const platform = platformMap[page];
    const isBound = userInfo.value[platform.key];
    
    if (isBound) {
      // 解绑账号
      uni.showModal({
        title: `解绑${platform.name}`,
        content: `确定要解绑${platform.name}账号吗？`,
        success: (res) => {
          if (res.confirm) {
            // 更新绑定状态
            userInfo.value[platform.key] = false;
            
            // 保存更新后的用户信息
            saveUserInfo();
            
            uni.showToast({
              title: `${platform.name}解绑成功`,
              icon: 'success'
            });
          }
        }
      });
    } else {
      // 绑定账号
      uni.showModal({
        title: `绑定${platform.name}`,
        content: `即将跳转到${platform.name}授权页面`,
        success: (res) => {
          if (res.confirm) {
            // 模拟授权流程
            uni.showLoading({
              title: '授权中...'
            });
            
            setTimeout(() => {
              uni.hideLoading();
              
              // 更新绑定状态
              userInfo.value[platform.key] = true;
              
              // 保存更新后的用户信息
              saveUserInfo();
              
              uni.showToast({
                title: `${platform.name}绑定成功`,
                icon: 'success'
              });
            }, 1500);
          }
        }
      });
    }
    return;
  }
  
  // 其他设置项提示信息
  uni.showToast({
    title: `即将开发${page}功能`,
    icon: 'none'
  });
};

// 手机号码格式化显示（中间4位用*代替）
const maskPhone = (phone) => {
  if (!phone || phone.length < 11) return '未设置';
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

// 格式验证函数
const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

const validatePhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 确认注销账号
const confirmDeleteAccount = () => {
  uni.showModal({
    title: '注销账号',
    content: '注销后，账号数据将无法恢复！确定要注销账号吗？',
    confirmColor: '#f44336',
    success: (res) => {
      if (res.confirm) {
        // 二次确认
        uni.showModal({
          title: '二次确认',
          content: '请再次确认，注销账号操作不可撤销！',
          confirmColor: '#f44336',
          success: (res) => {
            if (res.confirm) {
              uni.showLoading({
                title: '处理中...'
              });
              
              setTimeout(() => {
                uni.hideLoading();
                
                // 清除本地存储
                uni.clearStorageSync();
                
                // 返回登录页
                uni.reLaunch({
                  url: '/pages/login/index'
                });
              }, 2000);
            }
          }
        });
      }
    }
  });
};
</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
  min-height: 100%;
}

.account-settings-page {
  min-height: 100vh;
  padding-bottom: 30px;
  
  .header {
    position: relative;
    padding: 15px;
    background-color: #fff;
    border-bottom: 1px solid rgba(44, 120, 115, 0.1);
    display: flex;
    justify-content: center;
    align-items: center;
    
    .back-btn {
      position: absolute;
      left: 15px;
      top: 50%;
      transform: translateY(-50%);
      width: 30px;
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      
      .back-icon {
        font-size: 20px;
        font-weight: bold;
        color: #2c7873;
      }
    }
    
    .page-title {
      font-size: 18px;
      font-weight: 600;
      color: #2c7873;
    }
  }
  
  .settings-container {
    padding: 15px;
    
    // 设置区块
    .settings-section {
      margin-bottom: 20px;
      
      .section-title {
        font-size: 15px;
        font-weight: 500;
        color: #8d6e63;
        margin-bottom: 10px;
        padding-left: 10px;
      }
      
      .settings-list {
        background-color: #fff;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        
        .settings-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px;
          border-bottom: 1px solid rgba(141, 110, 99, 0.05);
          
          &:last-child {
            border-bottom: none;
          }
          
          .item-label {
            font-size: 15px;
            color: #5d4037;
          }
          
          .item-left {
            display: flex;
            align-items: center;
            
            .social-icon {
              width: 24px;
              height: 24px;
              border-radius: 4px;
              font-size: 12px;
              display: flex;
              justify-content: center;
              align-items: center;
              margin-right: 12px;
              color: #fff;
              
              &.wx {
                background-color: #07C160;
              }
              
              &.wb {
                background-color: #E6162D;
              }
              
              &.qq {
                background-color: #12B7F5;
              }
            }
            
            .item-label {
              font-size: 15px;
              color: #5d4037;
            }
          }
          
          .item-right {
            display: flex;
            align-items: center;
            
            .avatar-preview {
              width: 36px;
              height: 36px;
              border-radius: 18px;
              margin-right: 8px;
            }
            
            .item-value {
              font-size: 14px;
              color: #8d6e63;
              margin-right: 8px;
            }
            
            .item-arrow {
              font-size: 20px;
              color: #bcaaa4;
            }
          }
        }
      }
    }
    
    // 注销账号按钮
    .delete-account {
      margin-top: 30px;
      height: 44px;
      background-color: #fff;
      border-radius: 12px;
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      text {
        font-size: 16px;
        font-weight: 500;
        color: #f44336;
      }
    }
  }
}

// 自定义昵称修改弹框
.nickname-popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  animation: fade-in 0.2s ease-out;
  
  @keyframes fade-in {
    from { opacity: 0; }
    to { opacity: 1; }
  }
  
  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  
  .popup-content {
    position: relative;
    width: 85%;
    max-width: 340px;
    background-color: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
    animation: popup-in 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    
    @keyframes popup-in {
      0% {
        opacity: 0;
        transform: scale(0.9);
      }
      100% {
        opacity: 1;
        transform: scale(1);
      }
    }
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 18px 20px;
      border-bottom: 1px solid #f0f0f0;
      
      .popup-title {
        font-size: 18px;
        font-weight: 600;
        color: #2c7873;
      }
      
      .close-btn {
        width: 30px;
        height: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        transition: background-color 0.2s;
        
        &:active {
          background-color: #f5f5f5;
        }
        
        .close-icon {
          font-size: 22px;
          color: #999;
          font-weight: 300;
        }
      }
    }
    
    .popup-body {
      padding: 20px;
      
      .input-wrapper {
        margin-bottom: 12px;
        
        .nickname-input {
          width: 100%;
          height: 46px;
          padding: 0 15px;
          background-color: #f8f8f8;
          border: 1px solid #e8e8e8;
          border-radius: 10px;
          font-size: 16px;
          color: #333;
          transition: all 0.3s ease;
          
          &:focus {
            border-color: #2c7873;
            background-color: #f2f8f7;
            box-shadow: 0 0 0 2px rgba(44, 120, 115, 0.1);
          }
          
          &::placeholder {
            color: #aaa;
          }
        }
      }
      
      .input-tip {
        font-size: 13px;
        color: #8d6e63;
        margin-left: 3px;
      }
    }
    
    .popup-footer {
      display: flex;
      border-top: 1px solid #f0f0f0;
      
      .cancel-btn,
      .confirm-btn {
        flex: 1;
        height: 55px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 17px;
        font-weight: 500;
        transition: all 0.2s ease;
        
        &:active {
          opacity: 0.8;
        }
      }
      
      .cancel-btn {
        color: #666;
        background-color: #f7f7f7;
      }
      
      .confirm-btn {
        color: #fff;
        background: linear-gradient(135deg, #6FB3B8, #2c7873);
        
        &:active {
          background: linear-gradient(135deg, #62a1a6, #256761);
        }
      }
    }
  }
}
</style> 